<template>
  <el-dialog
    class="public-dialog"
    :title="`${isEdit ? '修改' : '新增'}`"
    width="560"
    :modelValue="modelValue"
    @close="handleClose"
    draggable
    align-center
  >
    <div class="h-[440px]" v-loading="loading">
      <VForm
        ref="form"
        :model="model"
        :fieldList="fieldList"
        :options="formOption"
        :rules="rules"
        :disabled="disabled"
        :originOption="{ ...optionsData, ...options }"
      >
        <template #bill_size="{ value, input }">
          <BillSize :value="value" @input="input" :options="optionsData" />
        </template>
      </VForm>
    </div>
    <template #footer>
      <div class="dialog-button">
        <el-button :disabled="loading" @click="handleClose(false)">
          {{ disabled ? '关闭' : '取消' }}
        </el-button>
        <el-button
          v-if="!disabled"
          type="primary"
          :loading="loading"
          @click="handleSave"
        >
          保存
        </el-button>
      </div>
    </template>
  </el-dialog>
</template>

<script setup lang="jsx">
import { ElMessage } from 'element-plus'
import VForm from '@/components/Form/index.vue'
import BillSize from '@/components/BillDialog/BillSize/index.vue'

import { overallOptions } from '@/api/public'
import { strHump } from '@/utils/index'

import {
  billInvoiceDetail,
  updateBillInvoice,
  createBillInvoice,
} from '../api'

const props = defineProps({
  id: { type: [String, Number], default: '' },
  modelValue: { type: Boolean, default: false },
  disabled: { type: Boolean, default: false },
  options: { type: Object, default: () => ({}) },
})

const emit = defineEmits(['update:modelValue', 'refresh', 'close'])

const formOption = {
  inline: true,
  labelPosition: 'top',
}

const rules = {
  model_name: [{ required: true, message: '请输入模板名称', trigger: 'blur' }],
  model_type: [{ required: true, message: '请选择模板类型', trigger: 'blur' }],
  use_platform: [
    { required: true, message: '请选择使用平台', trigger: 'blur' },
  ],
  is_default: [{ required: true, message: '请选择是否默认', trigger: 'blur' }],
  bills_id: [{ required: true, message: '请输入面单名称', trigger: 'blur' }],
  bill_size: [{ required: true, message: '请选择标签尺寸', trigger: 'blur' }],
}

const form = ref()
const model = ref({})
const loading = ref()
const optionsData = ref({})

const handleChangeBill = async e => {
  console.warn(e)
  const { options } = props
  const _data = options['billTemplate']
  const _item = _data?.find(n => n.bills_id === e)
  const { bill_size_l, bill_size_w } = _item || {}
  if (!bill_size_l || !bill_size_w) return
  const formValues = await form.value.getFormValues()
  model.value = Object.assign({}, formValues, {
    bill_size: { bill_size_l, bill_size_w },
  })
}

const publicStyle = { style: { width: '502px' } }
const fieldList = [
  {
    field: 'model_name',
    label: '模板名称',
    ...publicStyle,
  },
  {
    field: 'model_type',
    label: '模板类型',
    type: 'select',
    style: { width: '245px' },
    originField: 'model_type',
  },
  {
    field: 'use_platform',
    label: '使用平台',
    type: 'select',
    style: { width: '245px' },
    originField: 'use_platform',
  },
  {
    field: 'is_default',
    label: '是否默认',
    type: 'radio',
    options: {
      data: [
        { label: '是', value: 1 },
        { label: '否', value: 0 },
      ],
    },
  },
  {
    field: 'bills_id',
    label: '发票模板',
    ...publicStyle,
    type: 'select',
    originField: 'billTemplate',
    options: {
      valueKey: 'bills_id',
      labelKey: 'bill_name',
    },
    itemProps: { onChange: handleChangeBill },
  },
  {
    field: 'bill_size',
    label: '标签尺寸',
    ...publicStyle,
    slot: 'bill_size',
  },
  {
    field: 'remark',
    label: '备注',
    full: true,
    type: 'textarea',
    autosize: { minRows: 2, maxRows: 4 },
    itemStyle: { width: '100%', marginRight: 0 },
  },
]

onMounted(() => {
  getOptions()
})

const getOptions = async () => {
  try {
    const bill = 'base.bill'
    const { data } = await overallOptions({
      params: [bill],
    })
    const billSize = data?.[strHump(bill)]
    if (billSize) {
      optionsData.value = {
        ...data?.[strHump(bill)],
      }
    }
  } catch (e) {
    console.error(e)
  }
}

watch(
  () => props.id,
  val => {
    nextTick(() => {
      if (val) getDetail(val)
    })
  }
)

const getDetail = async id => {
  try {
    loading.value = true
    const { data } = await billInvoiceDetail({
      id,
    })

    const { bill_size_l, bill_size_w, ...reset } = data
    model.value = {
      ...reset,
      bill_size: {
        bill_size_l,
        bill_size_w,
      },
    }
  } catch (e) {
    console.error(e)
  } finally {
    loading.value = false
  }
}

const isEdit = computed(() => {
  return !!props.id
})

const handleSave = async () => {
  try {
    const { bill_size, ...formInfo } = await form.value.submit()
    const api = {
      edit: updateBillInvoice,
      add: createBillInvoice,
    }
    const { id } = props
    const { code, message } = await api[isEdit.value ? 'edit' : 'add']({
      id: id || undefined,
      ...formInfo,
      ...bill_size,
    })
    if (code !== 200) {
      ElMessage.warning(message)
      return
    }
    ElMessage.success(isEdit.value ? '修改成功' : '保存成功')
    handleClose(true)
  } catch (e) {
    if (e.toString().includes(false)) {
      ElMessage.warning('请检查表单信息')
    }
    console.error(e)
  } finally {
    loading.value = false
  }
}

const handleClose = async refresh => {
  model.value = {}
  await nextTick()
  form.value.resetForm()
  emit('update:modelValue', false)
  emit('close')
  if (refresh) emit('refresh')
}
</script>
